/*
 * SPDX-License-Identifier: BSD-3-Clause
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2023. All rights reserved.
 * Description   : udk spinlock interface
 */

#ifndef UDK_SPINLOCK_H
#define UDK_SPINLOCK_H

#include "udk_rwlock.h"

typedef struct {
    volatile int locked; /* lock status 0 = unlocked, 1 = locked */
} udk_spinlock_t;

/* initialize spinlock in static way */
#define UDK_SPINLOCK_INITIALIZER { 0 }

static inline void udk_spinlock_init(udk_spinlock_t *sl)
{
    sl->locked = 0;
}

static inline void udk_spinlock_lock(udk_spinlock_t *sl)
{
    int exp = 0;

    while (!__atomic_compare_exchange_n(&sl->locked, &exp, 1, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
        while (__atomic_load_n(&sl->locked, __ATOMIC_RELAXED) != 0) {
            udk_pause();
        }
        exp = 0;
    }
}

static inline void udk_spinlock_unlock(udk_spinlock_t *sl)
{
    __atomic_store_n(&sl->locked, 0, __ATOMIC_RELEASE);
}

static inline int udk_spinlock_trylock(udk_spinlock_t *sl)
{
    int exp = 0;
    return __atomic_compare_exchange_n(&sl->locked, &exp, 1, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED);
}

#endif